import { defineStore } from 'pinia'
import { api } from '@/utils/api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: false,
    permissions: [],
    isRefreshing: false, // 添加刷新标记，避免重复请求
    lastRefreshTime: 0   // 记录最后刷新时间
  }),

  getters: {
    getUser: (state) => state.user,
    getToken: (state) => state.token,
    isLoggedIn: (state) => state.isAuthenticated && state.token,
    getUserRole: (state) => state.user?.role || 'viewer',
    hasPermission: (state) => (permission) => {
      if (state.user?.role === 'admin') return true
      return state.permissions.includes(permission)
    }
  },

  actions: {
    // 登录
    async login(credentials) {
      try {
        const response = await api.auth.login(credentials)
        const { token, user } = response.data
        
        this.token = token
        this.user = user
        this.isAuthenticated = true
        this.permissions = user.permissions || []
        
        // 保存到localStorage
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(user))
        
        return { success: true, user }
      } catch (error) {
        console.error('登录失败:', error)
        this.logout()
        throw error
      }
    },

    // 注册
    async register(userData) {
      try {
        const response = await api.auth.register(userData)
        const { token, user } = response.data
        
        this.token = token
        this.user = user
        this.isAuthenticated = true
        this.permissions = user.permissions || []
        
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(user))
        
        return { success: true, user }
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    // 退出登录
    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      this.permissions = []
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    // 刷新用户信息
    async refreshUser() {
      if (!this.token || this.isRefreshing) return
      
      // 如果最近5分钟内已经刷新过，跳过请求
      const now = Date.now()
      if (now - this.lastRefreshTime < 5 * 60 * 1000) {
        return
      }
      
      try {
        this.isRefreshing = true
        const response = await api.auth.me()
        this.user = response.data
        this.permissions = response.data.permissions || []
        this.lastRefreshTime = now
        localStorage.setItem('user', JSON.stringify(response.data))
      } catch (error) {
        console.error('刷新用户信息失败:', error)
        this.logout()
        throw error
      } finally {
        this.isRefreshing = false
      }
    },

    // 初始化认证状态
    initAuth() {
      const token = localStorage.getItem('token')
      const user = localStorage.getItem('user')
      
      if (token && user) {
        try {
          this.token = token
          this.user = JSON.parse(user)
          this.isAuthenticated = true
          this.permissions = this.user.permissions || []
          
          // 只在必要时验证token（比如token快过期或距离上次验证超过1小时）
          const shouldRefresh = !this.lastRefreshTime || 
                               (Date.now() - this.lastRefreshTime > 60 * 60 * 1000)
          
          if (shouldRefresh) {
            this.refreshUser().catch(() => {
              this.logout()
            })
          }
        } catch (error) {
          console.error('初始化认证状态失败:', error)
          this.logout()
        }
      }
    },

    // 修改密码
    async changePassword(oldPassword, newPassword) {
      try {
        // 后端期望字段为 currentPassword 和 newPassword
        await api.auth.changePassword({ currentPassword: oldPassword, newPassword })
        return { success: true }
      } catch (error) {
        console.error('修改密码失败:', error)
        throw error
      }
    },

    // 忘记密码
    async forgotPassword(email) {
      try {
        await api.auth.forgotPassword({ email })
        return { success: true }
      } catch (error) {
        console.error('发送重置密码邮件失败:', error)
        throw error
      }
    },

    // 重置密码
    async resetPassword(token, newPassword) {
      try {
        await api.auth.resetPassword({ token, newPassword })
        return { success: true }
      } catch (error) {
        console.error('重置密码失败:', error)
        throw error
      }
    }
  }
})